#include "network/include/VsomeipServer.h"
#include "trace/include/logger.h"

#include <csignal>
#include <sstream>

network::VsomeipServer *its_sample_ptr(nullptr);
void handle_signal(int _signal) 
{
    if (its_sample_ptr != nullptr &&(_signal == SIGINT || _signal == SIGTERM))
    {
        its_sample_ptr->stop();
    }
}

//export LD_LIBRARY_PATH=":/usr/local/lib/:/home/osboxes/zyx/ap_incubator/2_Build/output/build_vsomeip"

int main(int argc, char **argv) 
{
    bool use_tcp = false;
    bool isSaveLog = true;
    uint32_t cycle = 1000; // default 1s
    std::string configPath {"VSOMEIP_CONFIGURATION=../../config/udp_server.json"};

    std::string tcp_enable("--tcp");
    std::string udp_enable("--udp");
    std::string printLog("--log");
    std::string cycle_arg("--cycle");

    for (int i = 1; i < argc; i++) 
    {
        if (tcp_enable == argv[i]) 
        {
            use_tcp = true;
            configPath.assign("VSOMEIP_CONFIGURATION=../../config/tcp_server.json");
        }
        if (udp_enable == argv[i]) {
            use_tcp = false;
            configPath.assign("VSOMEIP_CONFIGURATION=../../config/udp_server.json");
        }

        if(printLog == argv[i])
        {
            isSaveLog = false;
        }

        if (cycle_arg == argv[i] && i + 1 < argc) {
            i++;
            std::stringstream converter;
            converter << argv[i];
            converter >> cycle;
        }
    }
    // putenv(const_cast<char*>(configPath.c_str()));
    BoostLog::initBoostLog(isSaveLog);


    signal(SIGINT, handle_signal);
    signal(SIGTERM, handle_signal);

    network::VsomeipServer its_sample(use_tcp);
    its_sample_ptr = &its_sample;

    if (its_sample.init()) 
    {
        its_sample.offer();
        its_sample.start();
        return 0;
    } 
    else 
    {
        return 1;
    }
}
